<?php


namespace App\Model\Logic;

use App\Exception\HttpException;
use Swoft\Bean\Annotation\Mapping\Bean;

/**
 * Class UploadLogic
 * @Bean(name="UploadLogic")
 * @package App\Model\Logic
 */
class UploadLogic
{
    public function upload($file){
        //文件验证
        $this->checkFile($file);
        $fn = $file->getClientFilename();
        // 取文件的扩展名
        $ext = substr($fn,strrpos($fn,'.'));
        // 生成文件名
        $filename = md5(time().$fn).$ext;
        // 移动文件到上传目录
        $saveName = '/uploads/'.date('Ymd').'/'.$filename;
        $file->moveTo('public'.$saveName);
        throw new HttpException('上传成功',0,['img'=>$saveName]);
    }

    private function checkFile($file){
        try {
            validate(['file' => $file], 'FileValidator');
        } catch (\Exception $e) {
            throw new HttpException($e->getMessage());
        }
        $mime = getimagesize($file->getFile());
        if (!$mime){
            throw new HttpException('文件类型不被允许12');
        }
        if (!in_array($mime['mime'],["image/gif","image/png","image/jpeg"])){
            throw new HttpException('文件类型不被允许13');
        }
    }
}
